//
//  ByteBufferReader.m
//  ByteBuf
//
//  Created by 周最新 on 15/8/29.
//  Copyright (c) 2015年 zzx. All rights reserved.
//

#import "ByteBufferReader.h"

@implementation ByteBufferReader

- (instancetype)initWithData:(NSData *)data
{
    if (self = [super init]) {
        if (data) {
            _data = data;
            _position = 0;
        }
    }
    return self;
}

- (char)readByte
{
    char value;
    
    NSData *data = [_data subdataWithRange:NSMakeRange(_position, sizeof(char))];
    [data getBytes:&value
            length:sizeof(char)];
    _position += sizeof(char);
    return value;
}

- (NSData *)readBytes:(uint16_t)length
{
    NSData *data = nil;
    if (length) {
        data = [_data subdataWithRange:NSMakeRange(_position, length)];
        _position += length;
    }
    return data;
}

- (uint16_t)readUInt16
{
    uint16_t value;
    
    NSData *data = [_data subdataWithRange:NSMakeRange(_position, sizeof(uint16_t))];
    [data getBytes:&value
            length:sizeof(int16_t)];
    _position += sizeof(uint16_t);
    return value;
}

- (uint32_t)readUInt32
{
    uint32_t value;
    
    NSData *data = [_data subdataWithRange:NSMakeRange(_position, sizeof(uint32_t))];
    [data getBytes:&value
            length:sizeof(uint32_t)];
    _position += sizeof(uint32_t);
    return value;
}

@end
